// pages/public/login/login.js
const http = require("../../../utils/httpUtils.js");
const RSA = require("../../../utils/wx_rsa.js");
const app = getApp();
Page({
    data: {
        navbarData: {
            showCapsule: 1, //是否显示左上角图标
            title: '' //导航栏 中间的标题
        },
        height: app.globalData.height * 2 + 20,
        loginType: 'pwd',
        send: true,
        loading: false,
        second: 60,
        opacity: 0.5,
        canIUse: wx.canIUse('button.open-type.getUserInfo')
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        wx.getSetting({
            success(res) {
                if (res.authSetting['scope.userInfo']) {
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称
                    wx.getUserInfo({
                        withCredentials: true,
                        success(res) {
                            // console.log(res)
                        }
                    })
                }
            }
        })
    },
    bindGetUserInfo(e) {
        if (typeof(e.detail.userInfo) == "object") {
            let _data = e.detail;
            if (app.globalData.session_key) {
                let userInfo = {
                    login_type: "weixinSmall",
                    encryptedData: _data.encryptedData,
                    session_key: app.globalData.session_key,
                    iv: _data.iv,
                    client: "weixinSmall"
                }
                this.toLogin(userInfo)
            } else {
                let that = this;
                wx.showModal({
                    title: '提示',
                    confirmText: '确定',
                    content: '没有获取到微信登录信息,请重试',
                    success(res) {
                        if (res.confirm) {
                            wx.getStorage({
                                key: 'session_key',
                                success: function(res) {
                                    let userInfo = {
                                        login_type: "weixinSmall",
                                        encryptedData: _data.encryptedData,
                                        session_key: res.data,
                                        iv: _data.iv,
                                        client: "weixinSmall"
                                    }
                                    that.toLogin(userInfo)
                                },
                            })
                        }
                    }
                })
            }
        } else {
            wx.showModal({
                title: '提示',
                showCancel: false,
                confirmText: '知道了',
                content: '小程序获取你的信息仅用于快捷登录，请选择允许',
            })
        }
    },
    formSubmit(e) {
        if (this.data.phone == undefined) {
            wx.showToast({
                title: '请输入手机号',
                icon: 'none',
                mask: true
            })
            return
        }
        if (this.data.phone.length != 11) {
            wx.showToast({
                title: '手机号格式错误',
                icon: 'none'
            })
            return
        }
        this.data.loading = true;
        this.data.remmber = e.detail.value.remmber //记录是否保存密码
        let userInfo = {}
        userInfo.login_type = this.data.loginType //登录方式：password|密码登录， verify|短信登录
        userInfo.phone = RSA.hex2b64(RSA.KEYUTIL.getKey(app.globalData.publicKey).encrypt(e.detail.value.phone)); //手机号
        userInfo.client = 'weixinSmall'
        if (this.data.loginType == 'sms') {
            userInfo.verify_code = e.detail.value.yzm //短信验证码（使用短信登录必填）   
            userInfo.login_type = 'verify'
        }
        if (this.data.loginType == 'pwd') {
            userInfo.password = RSA.hex2b64(RSA.KEYUTIL.getKey(app.globalData.publicKey).encrypt(e.detail.value.pwd)) //登录密码（使用密码登录必填）
            userInfo.login_type = 'password'
        }
        // console.log(userInfo)
        this.toLogin(userInfo)
    },
    inPhone(e) {
        this.setData({
            phone: e.detail.value
        })
    },
    //执行登陆流程
    toLogin(userInfo) {
        http._post('/api/user/login', userInfo, res => {
            if (res.data.code == 1) {
                //保存token 
                wx.setStorage({
                    key: 'token',
                    data: res.data.data,
                })
                app.globalData.token = res.data.data.Authorization;
                wx.setStorage({
                    key: 'nickname',
                    data: res.data.data.nickname
                })
                let pages = getCurrentPages() //获取加载的页面
                // console.log(pages[pages.length - 2])
                if (pages.length == 1) { // 跳转到首页
                    wx.switchTab({
                        url: "/pages/tabBar/specialty/specialty"
                    })
                } else { //如果是从确认订单页面进来的话返回2级
                    if (`${pages[pages.length - 2].route}` == "pages/public/confirm-order/index") {
                        wx.navigateBack({
                            delta: 2
                        })
                    } else {
                        wx.navigateBack({
                            success() {
                                pages[pages.length - 1].onLoad()
                            }
                        })
                    }
                }
            } else {
                wx.showModal({
                    title: '提示',
                    content: res.data.msg
                })
            }
        })
    },
    showSendMsg() {
        if (!this.data.alreadySend) {
            this.setData({
                send: true
            })
        }
    },
    hideSendMsg() {
        this.setData({
            send: false,
        })
    }, //获取验证码
    sendMsg: function() {
        // console.log(this.data.phone)
        if (this.data.phone == undefined) {
            wx.showToast({
                title: '请输入手机号',
                icon: 'none',
                mask: true
            })
            return
        }
        if (this.data.phone.length != 11) {
            wx.showToast({
                title: '手机号格式错误',
                icon: 'none'
            })
            return
        }
        http._get('/api/sendsms/sendsms', {
            phone: RSA.hex2b64(RSA.KEYUTIL.getKey(app.globalData.publicKey).encrypt(this.data.phone)),
            scene: 'verify_login',
            client: 'weixinSmall'
        }, res => {
            console.log(res);
            if (res.data.code == 1) {
                wx.showToast({
                    title: '获取成功请稍等',
                    icon: 'none'
                })
                this.setData({
                    send: false
                })
                this.timer()
            } else {
                wx.showModal({
                    title: '提示',
                    content: res.data.msg,
                    showCancel: false
                })
                return
            }
        })
    },
    //登录方式
    loginType() {
        if (this.data.loginType == 'pwd')
            this.setData({
                loginType: 'sms'
            })
        else {
            this.setData({
                loginType: 'pwd'
            })
        }
    },
    forget() { //忘记密码
        wx.navigateTo({
            url: '/pages/public/forget_password/forget_password',
        })
    },
    //手机号聚焦
    phonefocus() {
        this.setData({
            inPhone: true
        })
    },
    //密码聚焦
    pwdfocus() {
        this.setData({
            pwd: true
        })
    },
    //手机号失焦
    phoneblur() {
        this.setData({
            inPhone: false
        })
    },
    //密码失焦
    pwdblur() {
        this.setData({
            pwd: false
        })
    },
    //监听输入时
    pwdinput(event) {
        if (event.detail.cursor >= 5) {
            this.setData({
                opacity: 1
            })
        } else {
            this.setData({
                opacity: 0.5
            })
        }
    },
    //倒计时
    timer() {
        let promise = new Promise((resolve, reject) => {
            let setTimer = setInterval(
                () => {
                    this.setData({
                        second: this.data.second - 1
                    })
                    if (this.data.second <= 0) {
                        this.setData({
                            second: 60,
                            send: true
                        })
                        resolve(setTimer)
                    }
                }, 1000)
        })
        promise.then((setTimer) => {
            clearInterval(setTimer)
        })
    },
    //去注册
    register() {
        wx.navigateTo({
            url: '/pages/public/register/register',
        })
    }
})